package com.xingxin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingxin.entity.Permission;
import com.xingxin.service.PermissionService;
import com.xingxin.utils.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 权限表 前端控制器
 * </p>
 *
 * @author mrLiu
 * @since 2021-01-08
 */
@RestController
@RequestMapping("/menuList")
//@CrossOrigin(allowedHeaders = "*" ,allowCredentials = "true")
public class PermissionController {
    public static final Logger logger = LoggerFactory.getLogger(PermissionController.class);

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/query")
    @ResponseBody
    public Map<String, Object> getMenuList() {
        logger.info("==>PermissionController--getMenuList()--start");
        List<Map<String, Object>> data = new ArrayList<>();
        try {
            //查询一级分类
            List<Permission> firstList = permissionService.list(new QueryWrapper<Permission>().eq("ps_pid", "0"));
            if (CollectionUtils.isEmpty(firstList)) {
                return ResultUtils.resultMap("-1", "未配置一级分类菜单", null);
            }
            firstList.forEach(p -> {
                Map<String, Object> firstMap = new HashMap<>();
                firstMap.put("id", Optional.ofNullable(p.getPsId()));
                firstMap.put("authName", Optional.ofNullable(p.getPsName()));
                firstMap.put("path", Optional.ofNullable(p.getPsA()));
                //查询二级分类
                List<Permission> secondList = permissionService.list(new QueryWrapper<Permission>().eq("ps_pid", p.getPsId()));
                List<Map<String, Object>> secondData = new ArrayList<>();
                secondList.forEach(p2 -> {
                    Map<String, Object> secondMap = new HashMap<>();
                    secondMap.put("id", Optional.ofNullable(p2.getPsId()));
                    secondMap.put("authName", Optional.ofNullable(p2.getPsName()));
                    secondMap.put("path", Optional.ofNullable(p2.getPsA()));
                    secondData.add(secondMap);
                });
                firstMap.put("children", secondData);
                data.add(firstMap);
            });
            logger.info("==>PermissionController--getMenuList()--over,result is:{}", data);
            return ResultUtils.resultMap("0", "success", data);
        } catch (Exception e) {
            logger.error("==>PermissionController--getMenuList()--Exception is:{}", e);
            return ResultUtils.resultMap("-1", "Exception", null);
        }
    }
}

